package middleware

import (
	"github.com/casbin/casbin/v2"
	"github.com/gin-gonic/gin"
	"net/http"
)

// 全局 Casbin Enforcer，程序启动时初始化
var enforcer *casbin.Enforcer

func InitCasbin() error {
	var err error
	enforcer, err = casbin.NewEnforcer("configs/rbac_model.conf", "configs/rbac_policy.csv")
	if err != nil {
		return err
	}
	err = enforcer.LoadPolicy()
	return err
}

// CasbinAuth 权限中间件
func CasbinAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从 JWT 中获取用户名
		userClaims, exists := c.Get("user") // JWTAuthMiddleware 已经设置
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "user not found"})
			c.Abort()
			return
		}

		user, ok := userClaims.(string)
		if !ok || user == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid user"})
			c.Abort()
			return
		}

		obj := c.Request.URL.Path
		act := c.Request.Method

		ok, err := enforcer.Enforce(user, obj, act)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "enforce error"})
			c.Abort()
			return
		}

		if !ok {
			c.JSON(http.StatusForbidden, gin.H{"error": "no permission"})
			c.Abort()
			return
		}

		c.Next()
	}
}
